<template>
  <div class="wavelength-selection-chart">
    <div class="chart-title">
      <span class="title-text">{{ title }}</span>

      <!-- ✅ 单独导出图片按钮（可开关） -->
      <button
        v-if="showExportButton"
        class="export-btn"
        @click="downloadImage"
        :title="`导出 ${title} 为 PNG`"
      >
        导出图片
      </button>
    </div>

    <div ref="chartContainer" :style="{ width: '100%', height: chartHeight }"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "WavelengthSelectionChart",
  props: {
    title: { type: String, default: "波长选择吸光度曲线" },
    // 预处理后的完整光谱数据：二维数组或包含 data 字段的一维数据
    fullSpectrumData: { type: Array, default: () => [] },
    // 完整的 X 轴（波长点，建议字符串数组以保持一致）
    fullXAxisData: { type: Array, default: () => [] },
    // 选中的波长点（支持索引或实际波长值字符串）
    selectedWavelengths: { type: Array, default: () => [] },
    // 显示第几个样本
    sampleIndex: { type: Number, default: 0 },
    // 图高度
    chartHeight: { type: String, default: "300px" },
    // ✅ 是否显示“导出图片”按钮
    showExportButton: { type: Boolean, default: true },
    // ✅ 导出文件名（不含扩展名）
    exportFileName: { type: String, default: "" },
    // 可选：是否启用 ECharts 自带工具栏保存（与按钮二选一也可同时）
    enableToolbarSave: { type: Boolean, default: false },
  },
  data() {
    return { chart: null };
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose();
    window.removeEventListener("resize", this.handleResize);
  },
  watch: {
    fullSpectrumData: { handler() { this.updateChart(); }, deep: true },
    selectedWavelengths: { handler() { this.updateChart(); }, deep: true },
    sampleIndex() { this.updateChart(); },
    fullXAxisData() { this.updateChart(); },
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },
    updateChart() {
      if (!this.chart || !this.fullSpectrumData.length || !this.fullXAxisData.length) return;

      const sampleData = this.fullSpectrumData[this.sampleIndex];
      if (!sampleData) return;

      // 主曲线
      const fullSpectrumSeries = {
        name: "光谱曲线",
        type: "line",
        data: sampleData.data || sampleData,
        lineStyle: { width: 2 },
        symbol: "none",
        smooth: false,
      };

      // 选中点
      const selectedPointsData = [];
      if (this.selectedWavelengths?.length > 0) {
        this.selectedWavelengths.forEach((w) => {
          let idx = -1;
          const wStr = w.toString();
          // 优先按“实际波长值”匹配
          idx = this.fullXAxisData.findIndex((x) => x === wStr);
          // 不行再把 w 当作索引
          if (idx === -1 && typeof w === "number" && w >= 0 && w < this.fullXAxisData.length) {
            idx = w;
          }
          if (idx !== -1) {
            const actualW = this.fullXAxisData[idx] || wStr;
            const arr = sampleData.data && Array.isArray(sampleData.data) ? sampleData.data : sampleData;
            const y = Array.isArray(arr) ? arr[idx] : undefined;
            if (y !== undefined) selectedPointsData.push([actualW, y]);
          }
        });
      }

      const selectedPointsSeries = {
        name: "选中波长点",
        type: "scatter",
        data: selectedPointsData,
        symbolSize: 8,
        z: 10,
        showSymbol: selectedPointsData.length > 0,
      };

      const option = {
        tooltip: {
          trigger: "axis",
          formatter(params) {
            if (!params || !params.length) return "";
            let result = `波长: ${params[0].axisValue}nm<br/>`;
            params.forEach((p) => {
              if (p.seriesName === "选中波长点") {
                result += `${p.seriesName}: ${p.value[1]?.toFixed?.(4)}<br/>`;
              } else {
                result += `${p.seriesName}: ${Number(p.value)?.toFixed?.(4)}<br/>`;
              }
            });
            return result;
          },
        },
        legend: {
          data: selectedPointsData.length > 0 ? ["光谱曲线", "选中波长点"] : ["光谱曲线"],
          top: 10,
        },
        grid: { left: "3%", right: "4%", bottom: "15%", top: "12%", containLabel: true },
        // dataZoom: [
        //   { type: "inside", xAxisIndex: 0, filterMode: "none" },
        //   { type: "slider", xAxisIndex: 0, filterMode: "none", bottom: 5, height: 20 },
        // ],
        xAxis: {
          type: "category",
          data: this.fullXAxisData,
          name: "波长 (nm)",
          nameLocation: "middle",
          nameGap: 25,
          axisLabel: { interval: "auto", rotate: 0 },
        },
        yAxis: {
          type: "value",
          name: "吸光度",
          nameLocation: "middle",
          nameGap: 40,
          scale: true,
        },
        // 可选开启 ECharts 默认保存按钮
        toolbox: this.enableToolbarSave
          ? { right: 10, top: 10, feature: { saveAsImage: {} } }
          : undefined,
        series: selectedPointsData.length > 0
          ? [fullSpectrumSeries, selectedPointsSeries]
          : [fullSpectrumSeries],
      };

      this.chart.setOption(option, true);
    },
    handleResize() {
      if (this.chart) this.chart.resize();
    },

    /** ✅ 暴露给父组件：获取 Base64（用于拼 PDF） */
    getChartBase64() {
      if (!this.chart) return null;
      return this.chart.getDataURL({
        type: "png",
        pixelRatio: 2,       // 高清导出
        backgroundColor: "#fff",
      });
    },

    /** ✅ 单独导出 PNG 图片 */
    downloadImage() {
      const base64 = this.getChartBase64();
      if (!base64) return;

      const ts = new Date();
      const pad = (n) => (n < 10 ? "0" + n : "" + n);
      const stamp = `${ts.getFullYear()}${pad(ts.getMonth() + 1)}${pad(ts.getDate())}-${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(ts.getSeconds())}`;

      const name =
        (this.exportFileName && this.exportFileName.trim()) ||
        (this.title ? this.title.replace(/[\/\\:*?"<>|]/g, "_") : "chart");

      const a = document.createElement("a");
      a.href = base64;
      a.download = `${name}-${stamp}.png`;
      a.click();
    },
  },
};
</script>

<style scoped>
.wavelength-selection-chart {
  width: 100%;
  height: 100%;
}

.chart-title {
  position: relative;
  text-align: center; /* 保持标题居中 */
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.title-text {
  display: inline-block;
  padding: 0 40px; /* 给右侧按钮留空间 */
}

.export-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  padding: 2px 8px;
  background-color: #409eff;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
}
.export-btn:hover {
  background-color: #66b1ff;
}
</style>
